package com.ahstu.learning.SubjectActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by xuning on 2016/7/25.
 */
public class ImageLoader {

    private LruCache<String,Bitmap> mCaches;
    
  public ImageLoader()
    {
        int Maxmemory=(int) Runtime.getRuntime().maxMemory();
        int cacheSize=Maxmemory/2;
        mCaches=new LruCache<String,Bitmap>(cacheSize)
        {
            @Override
            protected int sizeOf(String key, Bitmap value) {


                return value.getByteCount() / 1024;
            }
        };
        
    }
    //增加到缓存
void AddBitmaptocache(String url, Bitmap bitmap)
{
    if(getBitmap(url)==null)
        mCaches.put(url,bitmap);
    
    
}
    //从缓存获取
Bitmap getBitmap(String url)
{
   return mCaches.get(url) ;
    
}
    
    
    
    
    void showAsytask(ImageView imageView, String url)
    {
        Bitmap bitmap=getPicture(url);
        if(bitmap==null) {
            new ImageAsyTask(imageView,url).execute(url);
        }
       else
            imageView.setImageBitmap(bitmap);
    }
    
    


    public Bitmap getPicture(String path) {
        Bitmap bm = null;
        try {
            URL url = new URL(path);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            bm = BitmapFactory.decodeStream(is);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return bm;
    }
    
    class ImageAsyTask extends AsyncTask<String,Void,Bitmap>
    {
      private ImageView imageView;
       private String url; 
        
      public   ImageAsyTask(ImageView imageView, String url)
      {
         this.imageView=imageView;
          this.url=url;
          
      }
        @Override
        protected Bitmap doInBackground(String... strings) {
            String url=strings[0];
            
            Bitmap bitmap=getPicture(url);
            if(bitmap!=null)
            {
                AddBitmaptocache(url,bitmap);
                
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
           imageView.setImageBitmap(bitmap);
        }
    }
    
}
